import traceback
from ability.format import CustomResponse
from rest_framework import mixins, viewsets, request, permissions
import ability.permissions as pm
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from webevent.serializers import *
from django.http import HttpResponse
from rest_framework.response import Response
from ability.models import *
import webevent.events as eventclass


class WebEventCreateViewSet(mixins.CreateModelMixin, GenericViewSet):
  
  serializer_class = WebEventCreateSerializer
  permission_classes = [pm.CustomIsAuthenticated, pm.AdminPermission|pm.StudentPermission]

  def __init__(self, **kwargs):
    self.response_format = CustomResponse().response
    super(WebEventCreateViewSet, self).__init__(**kwargs)

  def create(self, request, *args, **kwargs):
    try:
      super(WebEventCreateViewSet, self).create(request, *args, **kwargs)
      self.response_format['message'] = 'success'
    except Exception as err:
      self.response_format["error_code"] = 201
      self.response_format["message"] = str(err)
    return Response(self.response_format)

class WebEventTeaListViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    queryset = School.objects.all()
    serializer_class = WebEventSerializer 
    permission_classes = [pm.CustomIsAuthenticated, pm.AdminPermission|pm.TeacherPermission]
    def __init__(self, **kwargs):
        self.response_format = CustomResponse().response
        super(WebEventTeaListViewSet, self).__init__(**kwargs)

    def get_queryset(self):
      try:
        userid = self.request.query_params.get('userid', None)
        event_type = self.request.query_params.get('event_type', None)
        course_id = self.request.query_params.get('course_id', None)

        if userid is None or event_type is None or course_id is None:
          raise Exception('参数不正确')

        course = Course.objects.filter(id=course_id).first()
        if course is None:
          raise Exception('数据不存在')

        ext_pk = []
        eventset = eventclass.get_events_of_types(event_type)
        if event_type == 'course':
          ext_pk = [course_id]

        if event_type == 'experiment':
          ext_pk = course.experiment_set.all()

        return WebEnvents.objects.filter(user_id=userid, ext_pk__in=ext_pk, event__in=eventset).order_by('-create_ts')
      except Exception as e:
        traceback.print_exc()
        self.response_format['message'] = str(e)
        return Response(self.response_format)